package cn.wizzer.app.web.commons.ext.websocket.action.msg.attendant;

import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.UserChatMsg;
import cn.wizzer.app.user.modules.models.enums.MsgTypeEnum;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.UserChatMsgService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ext.websocket.filter.AttendantFilter;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zl
 * @date 2020/7/3 10:14
 */
@IocBean
@NettyAction(uri = "/attendant/attendant/sendAll", filters = {TokenFilter.class, AttendantFilter.class})
public class AttendantSendAllAction extends BaseNettyAction {

    @Inject
    @Reference
    private UserService userService;
    @Inject
    private UserChatMsgService chatMsgService;

    @Override
    public Result action(Channel income, JSONObject params) {
        ChatUserVO attendant = NettyCache.globalGet(params.get("appid"));
        List<User> users = new ArrayList<>();
        if(attendant.getUsers() == null || attendant.getUsers().size() == 0){
            //当列表中无用户时查询最近会话
            attendant.setUsers(chatMsgService.findRecentChatUser(attendant.getId()));
        }
        if(attendant.getUsers().size() > 0){
            for (String userId : attendant.getUsers()) {
                User user = userService.fetch(userId);
                UserChatMsg msg = new UserChatMsg();
                String content = "我是客服，我叫：" + attendant.getNickName() +
                        "我在" + Times.format("yyyy-MM-dd HH:mm:ss", Times.now()) + "的时候发送消息给用户：" + user.getNickName();
                msg.setContent(content);
                msg.setCtAt(System.currentTimeMillis());
                msg.setToUser(userId);
                msg.setUserId(attendant.getId());
                msg.setType(MsgTypeEnum.TEXT);
                msg = chatMsgService.insert(msg);

                ChatUserVO target = NettyCache.globalGet(userId);
                if(target != null){
                    //发给用户
                    NettyMsgUtil.send(target.getChannel(), ChatResult.MessageTypeEnum.ATTENDANT, ChatResult.ActionEnum.SEND, attendant, JSONUtil.toJSONString(msg));
                    //该用户对应的客服，若没有客服则将用户的对应客服设置为自己
                    String targetAttendantId = NettyCache.localGet(target.getChannel(), "targetAttendant");
                    if(targetAttendantId == null){
                        //缓存指定客服
                        NettyCache.localSet(target.getChannel(),"targetAttendant", attendant.getId());
                    }
                }
            }
        }
        return Result.success();
    }
}
